<?php

namespace App\Admin\Forms;


use App\Models\Shop\WxShopOrder;
use App\Models\Shop\WxShopOrderAfter;
use App\Wen\Utils\ApiUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\ShopUtils;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;


class OrderForms extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * 处理表单请求.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {

        $id = $input['id'];
        $express_type = $input['express_type'];
        $express_no = $input['express_no'];
        $remark = $input['remark'];


        $express = '';
        $express_arr = ShopUtils::get_expree_name_range();
        foreach ($express_arr as $item){
            if($item['type'] == $express_type){
                $express = $item['name'];
                break;
            }
        }
        if(_empty_($express)){
            return $this->response()
                ->error('未查找到该快递公司')
                ->refresh();
        }


        $shop_order = WxShopOrder::find($id);
        if(!($shop_order->pay_status == 2 && in_array($shop_order->status, [1, 2]))){
            return $this->response()
                ->error('当前订单状态不可发货，修改物流信息等')
                ->refresh();
        }

        // 验证运单号是否可用
        $flag = true;
        if(!$flag){
            $appcode = Settings::get('app_ali_wuliu_appcode');//换成你自己阿里云的appcode
            if(_empty_($appcode)){
                return $this->response()
                    ->error('管理员未配置阿里物流查询接口')
                    ->refresh();
            }

            // 顺丰特殊情况
            if(_empty_($express_type)){
                $shop_order = WxShopOrder::where('express_no', $express_no)->first();
                if($shop_order){
                    $express_type = $shop_order->express_type;
                    if($express_type == 'SFEXPRESS'){
                        $adds_mobile = $shop_order->adds_mobile;
                        if($adds_mobile){
                            $express_no .= ':'.substr($adds_mobile, -4);
                        }
                    }
                }
            }else{
                if($express_type == 'SFEXPRESS'){
                    $adds_mobile = WxShopOrder::where('express_no', $express_no)->where('express_type', $express_type)->value('adds_mobile');
                    if($adds_mobile){
                        $express_no .= ':'.substr($adds_mobile, -4);
                    }
                }
            }


            $res = ApiUtils::ali_request($appcode, 'https://wuliu.market.alicloudapi.com/kdi', ['no'=>$express_no, 'type' => $express_type ]);
            if($res){
                if($res && $res['status'] == 0){
                    $flag = true;
                }else{
                    return $this->response()
                        ->error($res['msg'])
                        ->refresh();
                }
            }
            if(!$flag){
                return $this->response()
                    ->error('未查找到物流信息')
                    ->refresh();
            }
        }

        DB::beginTransaction();
        try {
            // todo:
            $ship_at = date('Y-m-d H:i:s', time());
            WxShopOrder::where('id', $id)->update([
                'express' => $express,
                'express_no' => $express_no,
                'express_type' => $express_type,
                'remark' => $remark,
                'ship_at' => $ship_at,
                'status' => 2,
            ]);

            $oinfo = WxShopOrder::where('id', $id)->first();

            $nr = '您的订单：' . $oinfo['order_id'] . ' 由：' . $express . '：「<a href="/pagesA/shop/logistics/logistics?nu='.$express_no.'&type='.$express_type.'">' . $express_no . '</a>」已经发出了。';

            // 发送通知
            UserUtils::add_user_notice(6001, $oinfo['user_id'], '商品发货通知', $nr, 100, '', $id);

            // 处理售后的催货
            WxShopOrderAfter::where([
                ['order_id', '=', $oinfo['order_id']],
                ['title', '=', '催发货']
            ])->update([
                'state' => 1,
            ]);

            Cache::forget('total:todo:count');
            Cache::forget('total:tenant:todo:count');
            DB::commit();

            return $this->response()
                ->success('发货成功')
                ->refresh();
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->response()
                ->error($e->getMessage());
        }


    }

    /**
     * 构建表单.
     */
    public function form()
    {
        $shopOrder = WxShopOrder::find($this->payload["id"]);
        $range = ShopUtils::get_expree_name_range();
        $range_options = [];
        foreach ($range as $item){
            $range_options[$item['type']] = $item['name'];
        }
        if($shopOrder){
            $this->html(function () use ($shopOrder) {
                return '<div>收货人：'.$shopOrder->adds_name.'<br>手机号：'.$shopOrder->adds_mobile.'<br>详细地址：'.$shopOrder->address.'</div>';
            }, '<b>用户收货地址</b>');
            $this->hidden('id')->value($shopOrder->id);
            $this->select('express_type', "物流名称")->options($range_options)->default($shopOrder->express_type);
            $this->text('express_no', "物流单号")->default($shopOrder->express_no);
            $this->textarea('remark', "备注");
        }

    }

}
